Ext.ns('ru.proburo.oms.dao');

/**
 * ru.proburo.oms.dao.JsonStore
 * @extends Ext.data.Store
 */
ru.proburo.oms.dao.JsonStore = Ext.extend(Ext.data.Store, {
    constructor: function(config)
	{
		config = config || {};
		
        Ext.applyIf(config, {
            method: 'POST',
			reader: new Ext.data.JsonReader({
				fields:          config.fields,
                idProperty:      'id',
				root:            'items',
				successProperty: 'success',
				totalProperty:   'totalCount'
			}),
			writer: new Ext.data.JsonWriter({
				encode:         true,
				listful:        true,
				writeAllFields: true
			}),
            
			autoSave:   false,
			remoteSort: true
        });
        
		ru.proburo.oms.dao.JsonStore.superclass.constructor.call(this, config);
    },
	saveRecord: function(record)
	{
		if (!this.writer) {
			throw new Ext.data.Store.Error('writer-undefined');
		}
		
		var queue = [],
			len,
			trans,
			batch,
			data = {};
		
		// DESTROY:  First check for removed records.  Records in this.removed are guaranteed non-phantoms.  @see Store#remove
		if(this.removed.indexOf(record) !== -1){
			queue.push(['destroy', record]);
		}
		// Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
		var rs = [].concat(this.getModifiedRecords());
		if(rs.indexOf(record) !== -1){
			
			if(record.phantom === true)
			{
				queue.push(['create', [record]]);
			}
			else
			{
				queue.push(['update', [record]]);
			}
		}
		
		len = queue.length;
		if(len){
			batch = ++this.batchCounter;
			for(var i = 0; i < len; ++i){
				trans = queue[i];
				data[trans[0]] = trans[1];
			}
			if(this.fireEvent('beforesave', this, data) !== false){
				for(var i = 0; i < len; ++i){
					trans = queue[i];
					this.doTransaction(trans[0], trans[1], batch);
				}
				return batch;
			}
		}
		return -1;
	}
});